# -*- coding: utf-8 -*-
"""
Created on Fri Nov  4 11:02:30 2022

@author: LUO
"""
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
import pyqtgraph as pg
import numpy as np
import sys
import csv
import time
import os

class SampleCurve:
   def __init__(self, enabled=False):
      self.enalbed = enabled
      self.data = []
      self.rowData = []
      self.curve = None

   def enalbe(self):
      self.enabled = True

class PcrPlotter:
   def __init__(self, dataBuffer=[], testCycles=50, size=(900, 500)):

      self.maxCycles = testCycles

      # PyQtGraph plotwidget
      self.plt = pg.PlotWidget()
      self.vb = self.plt.getViewBox()
      self.plt.plotItem.addLegend(offset=(-8,-20))
      self.plt.resize(*size)
      self.plt.setBackground('w')
      self.plt.setMouseEnabled(x=False,y=False)
      self.plt.showGrid(x=True, y=True)
      self.plt.setXRange(0., testCycles, padding=0)
      self.plt.setLabel('left', 'Delta Rn')
      self.plt.setLabel('bottom', 'Cycle number', 'n')

      #self.vline = pg.InfiniteLine(angle=90, movable=False)
      #self.hline = pg.InfiniteLine(angle=0, movable=False)
      #self.plt.plotItem.addItem(self.vline)
      #self.plt.plotItem.addItem(self.hline)
      #self.moved = pg.SignalProxy(self.vb.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
      #self.clicked = pg.SignalProxy(self.plt.scene().sigMouseClicked, rateLimit=60, slot=self.mouseClicked)

      self.sampleCurve = [0] * 8
      self.sampleCurve[0] = SampleCurve("False")
      self.sampleCurve[0].curve = self.plt.plot([], pen=(pg.mkPen((155,0,0),width=2)), name='Sample1')
      self.sampleCurve[1] = SampleCurve("False")
      self.sampleCurve[1].curve = self.plt.plot([], pen=(pg.mkPen((155,155,0),width=2)), name='Sample2')
      self.sampleCurve[2] = SampleCurve("False")
      self.sampleCurve[2].curve = self.plt.plot([], pen=(pg.mkPen((155,0,155),width=2)), name='Sample3')
      self.sampleCurve[3] = SampleCurve("False")
      self.sampleCurve[3].curve = self.plt.plot([], pen=(pg.mkPen((0,155,0),width=2)), name='Sample4')
      self.sampleCurve[4] = SampleCurve("False")
      self.sampleCurve[4].curve = self.plt.plot([], pen=(pg.mkPen((0,0,155),width=2)), name='Sample5')
      self.sampleCurve[5] = SampleCurve("False")
      self.sampleCurve[5].curve = self.plt.plot([], pen=(pg.mkPen((0,155,155),width=2)), name='Sample6')
      self.sampleCurve[6] = SampleCurve("False")
      self.sampleCurve[6].curve = self.plt.plot([], pen=(pg.mkPen((100,0,100),width=2)), name='Sample7')
      self.sampleCurve[7] = SampleCurve("False")
      self.sampleCurve[7].curve = self.plt.plot([], pen=(pg.mkPen((100,100,0),width=2)), name='Sample8')

      self.curve_Thre = self.plt.plot([1], pen=(255, 0, 0))

      self.first_some_point = []
      self.auto_avg = 0
      self.avg = [0.]*8

   def move(self, pos_x, pos_y):
      self.plt.move(pos_x, pos_y)

   def setTitle(self, str):
      self.plt.setTitle(str)

   def autoThreshold(self, buffer):
      #baseline = buffer[0:5]
      self.auto_avg = np.average(buffer)
      #self.auto_threshold = self.auto_avg + np.std(baseline) * 10.0
      self.auto_threshold = np.std(buffer) * 10.0
      x = np.linspace(0, self.maxCycles, self.maxCycles)
      y = [self.auto_threshold/self.auto_avg] * self.maxCycles

      #self.curve_Thre.setData(x,y)

   def updateCurve(self, sampleIndex, buffer):
      self.sampleCurve[sampleIndex].data = [x / self.auto_avg for x in buffer]
      self.sampleCurve[sampleIndex].curve.setData(self.sampleCurve[sampleIndex].data)

   def AddPointToCurve(self, sampleIndex, newPoint):
      if newPoint == 0:
         newPoint = 0.0000001

      self.sampleCurve[sampleIndex].rowData.append(newPoint)
      ''' #Strategy 1
      length = len(self.sampleCurve[sampleIndex].rowData)
      if length > 3:
         point = newPoint / self.avg[sampleIndex]
      elif length == 1:
         point = 1
      elif length == 2:
         point = self.sampleCurve[sampleIndex].rowData[1] / self.sampleCurve[sampleIndex].rowData[0]
      elif length == 3:
         self.avg[sampleIndex] = np.average(self.sampleCurve[sampleIndex].rowData)
         point = self.sampleCurve[sampleIndex].rowData[2] / self.avg[sampleIndex]

      self.sampleCurve[sampleIndex].data.append(point)
      self.sampleCurve[sampleIndex].curve.setData(self.sampleCurve[sampleIndex].data)
      #end strage 1
      '''
      # strategy 2
      if self.auto_avg == 0:
         # because the same sensor is used, so the static value could be common no matter the position
         if len(self.sampleCurve[sampleIndex].rowData) == 1:
            self.first_some_point.append(newPoint)
         else:
            if len(self.first_some_point) < 5:
               self.first_some_point = self.first_some_point + self.first_some_point

            self.autoThreshold(self.first_some_point)

         # plot the first point from 0
         self.sampleCurve[sampleIndex].data.append(1)
      else:
         self.sampleCurve[sampleIndex].data.append(newPoint/self.auto_avg)

      self.sampleCurve[sampleIndex].curve.setData(self.sampleCurve[sampleIndex].data)
      #end strategy 2

   def mouseMoved(self, evt):
      current_pos = self.vb.mapSceneToView(evt[0])
      if type(current_pos) != QtCore.QPointF:
         return
      self.currentMousePos = current_pos

   def mouseClicked(self, evt):
      if self.currentMousePos.x() > 0 and self.currentMousePos.y() > 0:
        self.vline.setPos(self.currentMousePos.x())
        self.hline.setPos(self.currentMousePos.y())
      print(self.currentMousePos)

   def writeCsv(self, sensor=''):
      if not os.path.exists("./Data"):
         os.mkdir("./Data")
      uuid_str = time.strftime("%Y-%m-%d_%H-%M-%S",time.localtime())
      log_path = './Data/%s.csv'%uuid_str
      file = open(log_path, 'a+', encoding='utf-8', newline='')
      csv_writer = csv.writer(file)
      csv_writer.writerow(['--%s--'%sensor])
      csv_writer.writerow(['Sample1'] + self.sampleCurve[0].rowData)
      csv_writer.writerow(['Sample2'] + self.sampleCurve[1].rowData)
      csv_writer.writerow(['Sample3'] + self.sampleCurve[2].rowData)
      csv_writer.writerow(['Sample4'] + self.sampleCurve[3].rowData)
      csv_writer.writerow(['Sample5'] + self.sampleCurve[4].rowData)
      csv_writer.writerow(['Sample6'] + self.sampleCurve[5].rowData)
      csv_writer.writerow(['Sample7'] + self.sampleCurve[6].rowData)
      csv_writer.writerow(['Sample8'] + self.sampleCurve[7].rowData)
      file.close()

   def clearAllBuffer(self):
      for i in range(0,8):
         self.sampleCurve[i].data =[]
         self.sampleCurve[i].curve.setData(self.sampleCurve[i].data)
         self.sampleCurve[i].rowData = []

      self.curve_Thre.setData([1])
      self.first_some_point = []
      self.auto_avg = 0

      print("Clear plotting buffer...")

# Add a main routine to test the object
if __name__ == "__main__":
   nums = [2.42, 2.45, 2.41, 2.42, 2.43, 2.44, 2.45, 2.47, 2.49, 2.51, 2.55, 2.60, 2.65, 2.66, 2.7]
   data1 = [0.009899974,0.011000037,0.003000021,0.001999974,0.001999974,0,0.003499985,0.003100038,0.004600048,0.00910008,0.018700004,0.03610003,0.052299976,0.076699972,0.09829998,0.118100047,0.138000011,0.150699973,0.160000086,0.16170001,0.164600015,0.169800043,0.17050004,0.173300028,0.174300075,0.170099974,0.173500061,0.172200084,0.174800038,0.172100067,0.171599984,0.170799971,0.172399998,0.174600005,0.172500014,0.173099995,0.174100041,0.173500061,0.173699975,0.175400019,0.177600026,0.175600052,0.177299976,0.180700064,0.179200053,0.178300023,0.180400014,0.183600068,0.183899999,0.185899973,]
   data2 = [0.00669992,0.008700013,0.004599929,0.004499912,0.002599955,0,0.004400015,0.007499933,0.005800009,0.012099981,0.020900011,0.037400007,0.05129993,0.074399948,0.094900012,0.118999958,0.131399989,0.141199946,0.152899981,0.150300026,0.152400017,0.158100009,0.154500008,0.15929997,0.156199932,0.153299928,0.156199932,0.154799938,0.156700015,0.158299923,0.154999971,0.153299928,0.15199995,0.151499987,0.152799964,0.150599957,0.148800015,0.147400022,0.148100019,0.15079999,0.149199963,0.148100019,0.151600003,0.152999997,0.147300005,0.146499991,0.146999955,0.149999976,0.149999976,0.151000023,]
   data3 = [0.014500022,0.009200096,0.005500078,0.004999995,0.003900051,0,0.000800014,0.003600001,0.002000093,0.002600074,0.00940001,0.016900063,0.022500038,0.040899992,0.056600094,0.08220005,0.099900007,0.118499994,0.136900067,0.141300082,0.149500012,0.158500075,0.154300094,0.159200072,0.156300068,0.157500029,0.160600066,0.156400084,0.157400012,0.159600019,0.154500008,0.155500054,0.155700088,0.158100009,0.155900002,0.154900074,0.155000091,0.156200051,0.157700062,0.156800032,0.159399986,0.154700041,0.152700067,0.154200077,0.15170002,0.149900079,0.152100086,0.151400089,0.149200082,0.152700067,]
   data4 = [0.016200066,0.0079,0.003900051,0.007799983,0.005100012,0,0.000400066,0.004600048,0.003499985,0.002300024,0.009799957,0.017799973,0.020300031,0.041200042,0.056599975,0.078400016,0.097499967,0.113900065,0.133900046,0.141700029,0.148200035,0.151200056,0.152999997,0.155099988,0.154899955,0.15139997,0.15320003,0.149500012,0.150099993,0.154000044,0.150200009,0.147899985,0.150699973,0.151900053,0.149000049,0.146200061,0.148300052,0.147400022,0.147099972,0.147300005,0.150900006,0.149399996,0.148599982,0.147400022,0.144799948,0.14139998,0.145400047,0.145200014,0.141900063,0.144999981,]
   data5 = [0.019199967,0.011700034,0.005900025,0.008399963,0.006700039,0.004400015,0.003900051,0.006899953,0,0.001000047,0.005499959,0.008299947,0.008200049,0.01820004,0.027500033,0.046499968,0.067000031,0.083500028,0.107599974,0.123000026,0.134699941,0.146499991,0.152099967,0.154899955,0.155400038,0.15320003,0.155200005,0.15049994,0.15199995,0.155400038,0.15079999,0.15049994,0.15049994,0.151499987,0.149099946,0.146999955,0.149000049,0.149199963,0.148100019,0.148100019,0.150300026,0.151499987,0.152999997,0.155499935,0.152500033,0.149199963,0.151600003,0.151499987,0.148000002,0.148000002,]
   data6 = [0.01910007,0.008300066,0.004500031,0.004000068,0.002799988,0.001399994,0,0.003499985,0.000499964,0.001000047,0.002300024,0.004400015,0.000800014,0.001000047,0.010400057,0.018300056,0.029500008,0.043799996,0.063899994,0.085900068,0.10619998,0.122500062,0.131200075,0.137600064,0.138800025,0.141299963,0.142500043,0.141299963,0.141700029,0.142799973,0.14199996,0.138000011,0.140799999,0.139100075,0.138100028,0.137699962,0.137799978,0.137400031,0.136999965,0.137899995,0.139299989,0.141700029,0.138900042,0.140500069,0.139700055,0.136299968,0.135900021,0.13470006,0.132600069,0.134000063,]
   baseline = nums[0:3]
   print(np.average(baseline) + 10*np.std(baseline))

   app = QtWidgets.QApplication(sys.argv)

   plotter=PcrPlotter()
   plotter.setTitle("探针1")

   w = QtWidgets.QMainWindow()
   w.setCentralWidget(plotter.plt)

   #plotter.autoThreshold(data1[0:5])
   for i in range(0, len(data1)):
      plotter.AddPointToCurve(0, data1[i])
      plotter.AddPointToCurve(1, data2[i])
      plotter.AddPointToCurve(2, data3[i])
      plotter.AddPointToCurve(3, data4[i])
      plotter.AddPointToCurve(4, data5[i])
      plotter.AddPointToCurve(5, data6[i])

   #for i in range(0, 50):
   #   plotter.AddPointToCurve(6, i*0.2)

   plotter.writeCsv('test')

   w.resize(900,500)

   w.show()

   sys.exit(app.exec_())
